package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.ShoppingCart;
import com.itheima.common.BaseContext;
import com.itheima.dao.ShoppingCartDao;
import com.itheima.service.ShoppingCartService;
import org.springframework.stereotype.Service;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartDao, ShoppingCart> implements ShoppingCartService {
    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart) {
        //条件构造器
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());

        //判断当前添加的是套餐还是菜品
        if(shoppingCart.getSetmealId() != null){
            //添加套餐id
            lqw.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }else {
            //添加菜品id
            lqw.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        }

        ShoppingCart cart = super.getOne(lqw);
        //将当前菜品或套餐的数据-1
        cart.setNumber(cart.getNumber() - 1);
        //判断当前菜品/套餐的数量是否为0
        if(cart.getNumber() == 0){
            //如果为0，则删除该菜品/套餐
            super.removeById(cart.getId());
        }else {
            super.updateById(cart);
        }

        return cart;
    }
    }

